use crate::models::currencies::{self, CreateParams};
use axum::{
    Json, Router,
    extract::State,
    routing::{get, post},
};
use loco_rs::prelude::*;

pub fn routes() -> Router<AppContext> {
    Router::new()
        .route("/currencies", post(create))
        .route("/currencies/:id", get(get_by_id))
        .route("/currencies/:id/delete", post(delete))
        .route("/currencies/by-code/:code", get(get_by_code))
}

async fn create(
    State(state): State<AppContext>,
    Json(params): Json<CreateParams>,
) -> Result<Response> {
    let currency = currencies::Model::create(&state.db, &params).await?;
    format::json(currency)
}

async fn get_by_id(State(state): State<AppContext>, Path(id): Path<String>) -> Result<Response> {
    let currency = currencies::Model::find_by_id(&state.db, &id).await?;
    format::json(currency)
}

async fn delete(State(state): State<AppContext>, Path(id): Path<String>) -> Result<Response> {
    let currency = currencies::Model::find_by_id(&state.db, &id).await?;
    currency.delete(&state.db).await?;
    format::json(())
}

async fn get_by_code(
    State(state): State<AppContext>,
    Path(code): Path<String>,
) -> Result<Response> {
    let currency = currencies::Model::find_by_code(&state.db, &code).await?;
    format::json(currency)
}
